#!/usr/bin/sh
echo "Mono Application deployment script"
echo "	by Alexey Prey Mulyukin (c) 2016"
echo "	email: alexprey@yandex.ru"
echo ""

APP_ROOT_DIR=$1
APP_DEPLOY_DIR=$2
APP_BUILD_CONFIGURATION=$3

if [ -z $APP_ROOT_DIR -a -z $APP_DEPLOY_DIR ]; then
	echo "Usage: sh deployApplication.sh APP_BUILD_DIR APP_DEPLOY_DIR APP_BUILD_CONFIGURATION"
	echo "	APP_ROOT_DIR			- directory with application root path for deployment"
	echo "	APP_DEPLOY_DIR			- destination directory for application deployment"
	echo "	APP_BUILD_CONFIGURATION	- Optional. The build configuration of application"
	exit 1
fi

if [ -z $APP_BUILD_CONFIGURATION ]; then
	APP_BUILD_CONFIGURATION=Release
fi

if [ ! -d $APP_ROOT_DIR ]; then
	echo "Application directory '$APP_ROOT_DIR' is not found"
	echo "Directory with built application should be exists!"
	exit 1
fi

if [ ! -d $APP_DEPLOY_DIR ]; then
	echo "Deploy directory '$APP_DEPLOY_DIR' not found"
	echo "Directory for deploying should be exists!"
	exit 1
fi

echo "Application path:	'$APP_ROOT_DIR'"
echo "Deployment path:	'$APP_DEPLOY_DIR'"

# Check already exists deployment scripts
if [ -d $APP_DEPLOY_DIR/_Deployment ]; then
	# Run uninstall script if exists
	if [ -f $APP_DEPLOY_DIR/_Deployment/uninstall.sh ]; then
		echo "Uninstall script found for '$APP_ROOT_DIR'"
		sh $APP_DEPLOY_DIR/_Deployment/uninstall.sh $APP_DEPLOY_DIR
	fi
fi

# Clear deploy directory from exists application
rm -Rf $APP_DEPLOY_DIR/*

# Copy application to deploy folder
cp -Rf $APP_ROOT_DIR/bin/$APP_BUILD_CONFIGURATION/* $APP_DEPLOY_DIR
if [ -d $APP_ROOT_DIR/_Deployment ]; then
	# Copy application specific deployment scripts
	mkdir $APP_DEPLOY_DIR/_Deployment
	cp $APP_ROOT_DIR/_Deployment/* $APP_DEPLOY_DIR/_Deployment
fi

# Remove unused files
rm -Rf $APP_DEPLOY_DIR/*.pdb
rm -Rf $APP_DEPLOY_DIR/*.mdb

# Check new deployment scripts
if [ -d $APP_DEPLOY_DIR/_Deployment ]; then
	# Run install script if exists
	if [ -f $APP_DEPLOY_DIR/_Deployment/install.sh ]; then
		echo "Install script found for '$APP_ROOT_DIR'"
		sh $APP_DEPLOY_DIR/_Deployment/install.sh $APP_DEPLOY_DIR
	fi
fi

echo "Application '$APP_ROOT_DIR' successfully deployed to '$APP_DEPLOY_DIR'"